import {
	Button,
	Collapse,
	Form,
	Input,
	Row,
	Col,
	TreeSelect,
	message,
} from 'antd'
import React, {memo, useState, useEffect} from 'react'
import {history, connect} from 'umi'
import styles from '@/assets/common/css/page.less'
import {translateDataToTree} from '@/utils/common/index'
import {getOnlydept} from '@/service/common/index'
import {addDept, editDept, viewDept} from '@/service/system/dept'

const {TextArea} = Input
const {Panel} = Collapse


const deptDom = memo((props: any) => {
	const currentMerchantId = props?.user?.currentMerchantId
	const [form] = Form.useForm()
	const [deptSource, setDeptSource] = useState<any[]>([])
	const [deptId, setDeptIdData] = useState()
	const [type, setType] = useState<string>()

	// 获取上级部门数据
	const onListFun = () => {
		getOnlydept({merchantId: currentMerchantId}).then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res?.data)
				const data: any = [
					{
						children: list,
						id: 0,
						parentId: 0,
						name: '根节点',
					},
				]
				setDeptSource(data as any)
			}
		})
	}

	// 获取部门详情
	const viewDeptFun = (id: string) => {
		viewDept(id).then((res: any) => {
			if (res?.success) {
				form.setFieldsValue({...res.data})
			}
		})
	}
	useEffect(() => {
		const {id, cid} = props.location.query
		const hrefs = window.location.href
		onListFun()
		if (hrefs.includes('view')) {
			setType('view')
		} else if (hrefs.includes('add')) {
			setType('add')
		} else {
			setType('edit')
		}
		if (!id && (cid || cid === 0)) {
			form.setFieldsValue({parentId: cid})
		}
		if (id) {
			setDeptIdData(id)
			viewDeptFun(id)
		}
	}, [])

	const submit = async () => {
		const fromData = await form.validateFields()
		if (!deptId) {
			// 新增角色
			addDept({...fromData}, currentMerchantId)
				.then((res: any) => {
					if (res.success) {
						message.success(res.msg)
						history.goBack()
					}
				})
				.catch((err: any) => {
					message.error(err)
				})
		} else {
			// 编辑角色
			editDept(deptId, {...fromData}, currentMerchantId)
				.then((res: any) => {
					if (res.success) {
						message.success(res.msg)
						history.goBack()
					}
				})
				.catch((err: any) => {
					message.error(err)
				})
		}
	}
	const customizeHeader = (value: string) => (
		<div>
			<div className={styles.tip} />
			{value}
		</div>
	)
	return (
		<div className={styles.page}>
			<div className={`${styles.content} ${styles.formDetils}`}>
				<Collapse
					defaultActiveKey={['1']}
					ghost
					expandIconPosition="end">
					<Panel header={customizeHeader('基础信息')} key="1">
						<Form
							name="basic"
							form={form}
							layout="horizontal"
							labelCol={{flex: '100px'}}
							initialValues={{remember: true}}
							disabled={type === 'view'}
							autoComplete="off">
							<Row gutter={12}>
								{type === 'add' ? (
									''
								) : (
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="编号"
											name="id"
											rules={[
												{
													required: true,
													message: '请输入编号',
												},
											]}>
											<Input
												placeholder="自动带出"
												disabled
											/>
										</Form.Item>
									</Col>
								)}
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="名称"
										name="name"
										rules={[
											{
												required: true,
												message: '请输入名称',
											},
										]}>
										{type === 'view' ? (
											<TextArea
												maxLength={20}
												placeholder="请输入（最多200个字）"
												autoSize={{
													minRows: 2,
													maxRows: 6,
												}}
											/>
										) : (
											<Input
												placeholder="请输入名称"
												maxLength={20}
											/>
										)}
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="上级部门"
										name="parentId"
										rules={[
											{
												required: true,
												message: '请输入上级部门',
											},
										]}>
										<TreeSelect
											showSearch
											treeNodeFilterProp="name"
											style={{width: '100%'}}
											dropdownStyle={{
												maxHeight: 400,
												overflow: 'auto',
											}}
											placeholder="请输入上级部门"
											allowClear
											treeDefaultExpandAll
											fieldNames={{
												label: 'name',
												value: 'id',
											}}
											treeData={deptSource}
										/>
									</Form.Item>
								</Col>
								<Col sm={{span: 24}} />
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item label="描述" name="description">
										<TextArea
											maxLength={200}
											placeholder="请输入（最多200个字）"
											autoSize={{minRows: 3, maxRows: 6}}
										/>
									</Form.Item>
								</Col>
							</Row>
						</Form>
					</Panel>
				</Collapse>
				<div className={styles.wrap}>
					{type !== 'view' ? (
						<Button
							type="primary"
							htmlType="submit"
							onClick={submit}>
							保存
						</Button>
					) : null}
					<Button
						onClick={(e) => {
							e.stopPropagation()
							history.goBack()
						}}>
						取消
					</Button>
				</div>
			</div>
		</div>
	)
})

export default connect(({user}: any) => ({
	user,
}))(deptDom)
